/*
Copyright (c) 2004-2008,

Sebastian Ryszard Kruk
http://www.sebastiankruk.com/

with contributions from (under the Corrib.org project):
Digital Enterprise Research Institute, 
National University of Ireland, Galway, Ireland
http://www.deri.org/

Faculty of Electronics, Telecommunication and Informatics and Main Library
Gdansk University of Technology, Poland
http://www.eti.pg.gda.pl/
http://www.bg.pg.gda.pl/


FOAFRealm is distributed under New BSD License.


All rights reserved.


Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, 
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, 
  this list of conditions and the following disclaimer in the documentation and/or 
  other materials provided with the distribution and reference to the source code. 
* Neither the name of Sebastian Ryszard Kruk nor the names of its contributors 
  (Digital Enterprise Research Institute, National University of Ireland, Galway, Ireland; 
  Faculty of Electronics, Telecommunication and Informatics and Main Library Gdansk University of Technology, Poland) 
  may be used to endorse or promote products derived from this software without specific prior written permission.


THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, 
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package cn.sh.library.gmwx.utils;

//import java.util.logging.Logger;


/**
 * 
 * 
 * @author Tomek Woroniecki, Sebastian Ryszard Kruk,
 * @created 14.07.2004
 */
public class Sha1sum {

//	private static final Logger log = Logger.getLogger(Sha1sum.class.getName());
	
	/** Convert a 32-bit number to a hex string with ms-byte first */
	String hex_chr = "0123456789abcdef";

	/** */
	protected static final Sha1sum instance = new Sha1sum();

	/** Constructor for the Sha1sum object */
	protected Sha1sum() {/**/
	}

	/*
	 * Take a string and return the hex representation of its SHA-1.
	 */
	/**
	 * Description of the Method
	 * 
	 * @param str
	 *            Description of Parameter
	 * @return Description of the Returned Value
	 */
	public String calc(String str) {
		int[] x = str2blks_SHA1(str);
		int[] w = new int[80];

		int a = 1732584193;
		int b = -271733879;
		int c = -1732584194;
		int d = 271733878;
		int e = -1009589776;

		for (int i = 0; i < x.length; i += 16) {
			int olda = a;
			int oldb = b;
			int oldc = c;
			int oldd = d;
			int olde = e;

			for (int j = 0; j < 80; j++) {
				if (j < 16) {
					w[j] = x[i + j];
				} else {
					w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
				}
				int t = safe_add(safe_add(rol(a, 5), ft(j, b, c, d)), safe_add(
						safe_add(e, w[j]), kt(j)));
				e = d;
				d = c;
				c = rol(b, 30);
				b = a;
				a = t;
			}

			a = safe_add(a, olda);
			b = safe_add(b, oldb);
			c = safe_add(c, oldc);
			d = safe_add(d, oldd);
			e = safe_add(e, olde);
		}
		String result = hex(a) + hex(b) + hex(c) + hex(d) + hex(e);

//		log.finest(				"SHA1SUM from :" + str + " => " + result);

		return result;
	}

	/**
	 * Description of the Method
	 * 
	 * @param num
	 *            Description of Parameter
	 * @return Description of the Returned Value
	 */
	private String hex(int num) {
		String str = "";
		for (int j = 7; j >= 0; j--) {
			str += hex_chr.charAt((num >> (j * 4)) & 0x0F);
		}
		return str;
	}

	/**
	 * Convert a string to a sequence of 16-word blocks, stored as an array.
	 * Append padding bits and the length, as described in the SHA1 standard.
	 * 
	 * @param str
	 *            Description of Parameter
	 * @return Description of the Returned Value
	 */
	private int[] str2blks_SHA1(String str) {
		int nblk = ((str.length() + 8) >> 6) + 1;
		int[] blks = new int[nblk * 16];
		for (int i = 0; i < nblk * 16; i++) {
			blks[i] = 0;
		}
		for (int i = 0; i < str.length(); i++) {
			blks[i >> 2] |= str.charAt(i) << (24 - (i % 4) * 8);
		}
		blks[str.length() >> 2] |= 0x80 << (24 - (str.length() % 4) * 8);
		blks[nblk * 16 - 1] = str.length() * 8;

		return blks;
	}

	/**
	 * Add integers, wrapping at 2^32. This uses 16-bit operations internally to
	 * work around bugs in some JS interpreters.
	 * 
	 * @param x
	 *            Description of Parameter
	 * @param y
	 *            Description of Parameter
	 * @return Description of the Returned Value
	 */
	private int safe_add(int x, int y) {
		int lsw = (x & 0xFFFF) + (y & 0xFFFF);
		int msw = (x >> 16) + (y >> 16) + (lsw >> 16);
		return (msw << 16) | (lsw & 0xFFFF);
	}

	/*
	 * Bitwise rotate a 32-bit number to the left
	 */
	/**
	 * Description of the Method
	 * 
	 * @param num
	 *            Description of Parameter
	 * @param cnt
	 *            Description of Parameter
	 * @return Description of the Returned Value
	 */
	private int rol(int num, int cnt) {
		return (num << cnt) | (num >>> (32 - cnt));
	}

	/*
	 * Perform the appropriate triplet combination function for the current
	 * iteration
	 */
	/**
	 * Description of the Method
	 * 
	 * @param t
	 *            Description of Parameter
	 * @param b
	 *            Description of Parameter
	 * @param c
	 *            Description of Parameter
	 * @param d
	 *            Description of Parameter
	 * @return Description of the Returned Value
	 */
	private int ft(int t, int b, int c, int d) {
		if (t < 20) {
			return (b & c) | ((~b) & d);
		}
		if (t < 40) {
			return b ^ c ^ d;
		}
		if (t < 60) {
			return (b & c) | (b & d) | (c & d);
		}
		return b ^ c ^ d;
	}

	/*
	 * Determine the appropriate additive constant for the current iteration
	 */
	/**
	 * Description of the Method
	 * 
	 * @param t
	 *            Description of Parameter
	 * @return Description of the Returned Value
	 */
	private int kt(int t) {
		return (t < 20) ? 1518500249 : (t < 40) ? 1859775393
				: (t < 60) ? -1894007588 : -899497514;
	}

	/**
	 * Gets the instance attribute of the Sha1sum class
	 * 
	 * @return The instance value
	 */
	public static Sha1sum getInstance() {
		return instance;
	}

	/**
	 * The main program for the Sha1sum class
	 * 
	 * @param args
	 *            The command line arguments
	 */
	public static void main(String[] args) {
//		log.finest(				"SHA1SUM('D0ndek') check: "						+ Sha1sum.getInstance().calc("D0ndek"));
//System.out.println(Sha1sum.getInstance().calc("mailto:haklae.kim@deri.org"));
	}
}
